package com.user.controller;

import java.util.Enumeration;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Timestamp;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.user.bean.*;
import com.user.service.*;

/*登录：LoginController*/
@Controller
public class LoginController {

//	注入UserService对象
	@Autowired
	private UserService userService;
	@RequestMapping("/login")
	public void login(HttpServletRequest request,HttpServletResponse response) throws Exception {
		try {
			String type = request.getParameter("type");
			String username = request.getParameter("username");
			String password = request.getParameter("password");
			if (username==null||username.equals("")||password==null||password.equals("")) {
				throw new Exception("用户名或密码不能为空");
			}
			Object login=null;
			if (type.equals("user")) {
				User user = new User();
				user.setUsername(username);
				user.setPassword(password);
				try {
					login=userService.findAll(user).get(0);
				} catch (Exception e) {
					throw new Exception("用户名和密码不匹配");
				}
			}			
			if (login!=null) {
				request.getSession().setAttribute(type, login);
				request.getSession().setAttribute("login", login);
				request.getSession().setAttribute("role", type);
				response.sendRedirect(request.getContextPath()+"/index.jsp");
				return;
			}else {
				throw new Exception("用户名和密码不匹配");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			request.setAttribute("msg", e.getMessage());
			request.getRequestDispatcher("/login.jsp").forward(request, response);
			return;
		}

	}
	@RequestMapping("/register")
	public void register(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String type = request.getParameter("type");
		try {
			try {
				request.getRequestDispatcher("/"+type+"/insert").forward(request, response);;
			} catch (Exception e) {
				throw new Exception(e.getMessage());
			}
		} catch (Exception e) {
			request.setAttribute("msg", e.getMessage().replace("添加", "注册"));
			request.getRequestDispatcher("/"+type+"Register.jsp").forward(request, response);
			return;
		}
	}
	@RequestMapping("/logout")
	public void logout(HttpServletRequest request,HttpServletResponse response) throws Exception {
		HttpSession session = request.getSession();
		Enumeration<String> enumeration = session.getAttributeNames();
		while (enumeration.hasMoreElements()) {
			String key = (String) enumeration.nextElement();
			session.removeAttribute(key);
		}
		response.sendRedirect(request.getContextPath()+"/login.jsp");
	}
}
